package com.jrfid.smartcabinet.demo.databinding

import android.view.View
import android.widget.*
import androidx.appcompat.widget.AppCompatSpinner
import androidx.core.widget.NestedScrollView
import androidx.databinding.BindingAdapter
import androidx.databinding.InverseBindingAdapter
import androidx.databinding.InverseBindingListener
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils

object DataBindingAdapter {

    @BindingAdapter("appendText")
    @JvmStatic
    fun appendText(textView: TextView, text: String) {
        if (text.isNotEmpty()) {
            LogUtils.d("append : ${text}")
            textView.append(text)
            textView.append("\n")
            if (textView.parent is NestedScrollView) {
                (textView.parent as NestedScrollView).fullScroll(ScrollView.FOCUS_DOWN)
            }
        }
    }

    @BindingAdapter("bindAdapter")
    @JvmStatic
    fun bindAdapter(recyclerView: RecyclerView, delegateAdapter: RecyclerView.Adapter<*>?) {
        if (delegateAdapter != null) {
            recyclerView.adapter = delegateAdapter
        }
    }

    @BindingAdapter("bindManager")
    @JvmStatic
    fun bindManager(recyclerView: RecyclerView, layoutManager: RecyclerView.LayoutManager?) {
        if (layoutManager != null) {
            recyclerView.layoutManager = layoutManager
        }
    }

    @BindingAdapter("select")
    @JvmStatic
    fun setSelectSpinnerPosition(spinner: AppCompatSpinner, position: Int) {
        if (spinner.selectedItemPosition != position)
            spinner.setSelection(position)
    }

    @InverseBindingAdapter(attribute = "select", event = "selectChange")
    @JvmStatic
    fun getSelectSpinnerPosition(spinner: AppCompatSpinner): Int {
        return spinner.selectedItemPosition
    }

    @BindingAdapter("selectChange")
    @JvmStatic
    fun setOnSpinnerCheckedChangeListener(spinner: AppCompatSpinner, bindingListener: InverseBindingListener?) {
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                bindingListener?.onChange()
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

        }
    }

}